package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.company.Company;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.vo.ContractProductVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/cargo/contract")
public class ContractController extends BaseController {

    @Reference
    private ContractService contractService;

    @RequestMapping(value = "/list" ,name = "分页查询购销合同列表数据")
    public String findAll(@RequestParam(value = "page",defaultValue = "1") Integer pageNum , @RequestParam(defaultValue = "10")Integer pageSize){


//        查询本企业的购销合同 where company_id=??  order by create_time desc
       ContractExample example = new ContractExample();
        ContractExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getCompanyId());


//       数据级别的细颗粒度权限控制
        User user = getUser();
        Integer degree = user.getDegree();
//        普通员工
        if(degree==4){
            criteria.andCreateByEqualTo(user.getId());
        }
//        部门经理
        else if(degree==3){
            criteria.andCreateDeptEqualTo(user.getDeptId());
        }
//        部门总经理
        else if(degree==2){
            criteria.andCreateDeptLike(user.getDeptId()+"%");
        }

        example.setOrderByClause("create_time desc");
        PageInfo pageInfo =  contractService.findAll(example,pageNum,pageSize);
       request.setAttribute("page",pageInfo);
       return "cargo/contract/contract-list";
    }

    @RequestMapping(value = "/toAdd",name = "跳转到新增购销合同页面")
    public String toAdd(){

        return "cargo/contract/contract-add";
    }

    @RequestMapping(value = "/edit",name = "保存购销合同信息")
    public String edit(Contract contract){

        if(StringUtils.isNotEmpty(contract.getId())){
//           id不为空，应该执行修改方法
            contractService.update(contract);
        }else{
            contract.setId(UUID.randomUUID().toString());
            contract.setCompanyId(getCompanyId());
            contract.setCompanyName(getCompanyName());
            contract.setState(0);
            contract.setCreateTime(new Date()); //创建时间 ,为了方便排序 新的购销合同排到前面
            contract.setCreateBy(getUser().getId()); //创建人id
            contract.setCreateDept(getUser().getDeptId());// 创建人部门id
            contractService.save(contract);
        }
        return "redirect:/cargo/contract/list.do"; // 重定向到列表页面
    }
    @RequestMapping(value = "/toUpdate",name = "跳转到修改购销合同页面")
    public String toUpdate(String id){
        Contract contract = contractService.findById(id);
        request.setAttribute("contract",contract);
//        新增和修改页面共用一个
        return "cargo/contract/contract-add";
    }
    @RequestMapping(value = "/delete",name = "删除购销合同数据")
    public String delete(String id){
        contractService.delete(id);
        return "redirect:/cargo/contract/list.do"; // 重定向到列表页面
    }

    @RequestMapping(value = "/print",name = "进入到导出出货表页面")
    public String print(){

        return "/cargo/print/contract-print";
    }


    @Autowired
    private DownloadUtil downloadUtil;


    @RequestMapping(value = "/printExcel",name = "导出出货表方法")
    public void printExcel(String inputDate) throws Exception{
       List<ContractProductVo> cpVoList = contractService.findContractProductVoListByShipTime(inputDate,getCompanyId());

//        创建了一个空的工作薄，里面什么都没有
        Workbook workbook = new XSSFWorkbook();
//        创建一个工作表 ,空的
        Sheet sheet = workbook.createSheet("出货表");
//        设置sheet的列宽
//        sheet.setColumnWidth(0,4200); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(1,26*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(2,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(3,26*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(4,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(5,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(6,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(7,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(8,16*256); //1代表一个字母宽度的256分之一


//   ---------------     设置大标题开始     -------------------
        Row bigTitleRow = sheet.createRow(0);
//        行高
        bigTitleRow.setHeightInPoints(36);
        for (int i = 1; i <= 8; i++) { //创建8个单元格
            bigTitleRow.createCell(i);
        }
//        合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));

        Cell cell = bigTitleRow.getCell(1);
        cell.setCellStyle(bigTitle(workbook));
//        2019-12:2019年12  月份出货表      2019-01:2019年1  月份出货表
//        向单元格中写一句话   2012年8月份出货表
        cell.setCellValue(inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表");
//   ---------------     设置大标题结束     -------------------

//   ---------------     设置小标题开始     -----------------
        Row titleRow = sheet.createRow(1);
        titleRow.setHeightInPoints(26);
//        客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
        String[] titles = new String[]{"客户","合同号","货号","数量","工厂","工厂交期","船期","贸易条款"};
        for (int i = 1; i <= 8; i++) {
            cell = titleRow.createCell(i);
            cell.setCellStyle(title(workbook));
            cell.setCellValue(titles[i-1]);
        }
//   ---------------     设置小标题结束     -----------------


 //   ---------------     设置内容开始     -----------------
        int rowIndex = 2;
        Row row = null;
        for (ContractProductVo contractProductVo : cpVoList) {
            row = sheet.createRow(rowIndex);
            row.setHeightInPoints(24);
//            客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
            cell = row.createCell(1);
            cell.setCellValue(contractProductVo.getCustomName()); // 客户
            cell.setCellStyle(text(workbook));

            cell = row.createCell(2);
            cell.setCellValue(contractProductVo.getContractNo()); //合同号
            cell.setCellStyle(text(workbook));

            cell = row.createCell(3);
            cell.setCellValue(contractProductVo.getProductNo());//货号
            cell.setCellStyle(text(workbook));

            cell = row.createCell(4);
            cell.setCellValue(contractProductVo.getCnumber());//数量
            cell.setCellStyle(text(workbook));

            cell = row.createCell(5);
            cell.setCellValue(contractProductVo.getFactoryName());//工厂
            cell.setCellStyle(text(workbook));

            cell = row.createCell(6);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getDeliveryPeriod()) );//工厂交期
            cell.setCellStyle(text(workbook));

            cell = row.createCell(7);
            cell.setCellValue( new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getShipTime()) );//船期
            cell.setCellStyle(text(workbook));

            cell = row.createCell(8);
            cell.setCellValue(contractProductVo.getTradeTerms());// 贸易条款
            cell.setCellStyle(text(workbook));
            rowIndex++;
        }

//   ---------------     设置内容结束     -----------------

//        一个流 输出流
//        两个头 mine类型 和 打开方式
//        return "/cargo/print/contract-print";


        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);

        downloadUtil.download(byteArrayOutputStream,response,"出货表.xlsx");

    }

    @RequestMapping(value = "/printExcelWithTemplate",name = "使用模板导出出货表方法")
    public void printExcelWithTemplate(String inputDate) throws Exception{
        List<ContractProductVo> cpVoList = contractService.findContractProductVoListByShipTime(inputDate,getCompanyId());

//        获取模板的路径
       String templateFilePath = session.getServletContext().getRealPath("/make/xlsprint/tOUTPRODUCT.xlsx"); //获取项目的根路径
//        读取模板创建一个有内容的工作薄
        Workbook workbook = new XSSFWorkbook(new FileInputStream(templateFilePath));
        Sheet sheet = workbook.getSheetAt(0);


        Cell cell = sheet.getRow(0).getCell(1);
        cell.setCellValue(inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表");

        //   ---------------     设置内容开始     -----------------

//        先把模板中的样式获取一下，放到一个数组中
        CellStyle[]  cellStyles = new CellStyle[8];
        Row row = sheet.getRow(2);
        for (int i = 1; i <= 8; i++) {
            cellStyles[i-1] =  row.getCell(i).getCellStyle();
        }

        int rowIndex = 2;

        for (ContractProductVo contractProductVo : cpVoList) {
            row = sheet.createRow(rowIndex);
            row.setHeightInPoints(24);
//            客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
            cell = row.createCell(1);
            cell.setCellValue(contractProductVo.getCustomName()); // 客户
            cell.setCellStyle(cellStyles[0]);

            cell = row.createCell(2);
            cell.setCellValue(contractProductVo.getContractNo()); //合同号
            cell.setCellStyle(cellStyles[1]);

            cell = row.createCell(3);
            cell.setCellValue(contractProductVo.getProductNo());//货号
            cell.setCellStyle(cellStyles[2]);

            cell = row.createCell(4);
            cell.setCellValue(contractProductVo.getCnumber());//数量
            cell.setCellStyle(cellStyles[3]);

            cell = row.createCell(5);
            cell.setCellValue(contractProductVo.getFactoryName());//工厂
            cell.setCellStyle(cellStyles[4]);

            cell = row.createCell(6);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getDeliveryPeriod()) );//工厂交期
            cell.setCellStyle(cellStyles[5]);

            cell = row.createCell(7);
            cell.setCellValue( new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getShipTime()) );//船期
            cell.setCellStyle(cellStyles[6]);

            cell = row.createCell(8);
            cell.setCellValue(contractProductVo.getTradeTerms());// 贸易条款
            cell.setCellStyle(cellStyles[7]);
            rowIndex++;
        }

//   ---------------     设置内容结束     -----------------

//        一个流 输出流
//        两个头 mine类型 和 打开方式
//        return "/cargo/print/contract-print";


        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream,response,"出货表.xlsx");

    }


    @RequestMapping(value = "/printExcelMillion",name = "百万数据导出")
    public void printExcelMillion(String inputDate) throws Exception{
        List<ContractProductVo> cpVoList = contractService.findContractProductVoListByShipTime(inputDate,getCompanyId());

//        创建了一个空的工作薄，里面什么都没有
        Workbook workbook = new SXSSFWorkbook();
//        创建一个工作表 ,空的
        Sheet sheet = workbook.createSheet("出货表");
//        设置sheet的列宽
//        sheet.setColumnWidth(0,4200); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(1,26*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(2,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(3,26*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(4,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(5,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(6,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(7,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(8,16*256); //1代表一个字母宽度的256分之一


//   ---------------     设置大标题开始     -------------------
        Row bigTitleRow = sheet.createRow(0);
//        行高
        bigTitleRow.setHeightInPoints(36);
        for (int i = 1; i <= 8; i++) { //创建8个单元格
            bigTitleRow.createCell(i);
        }
//        合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));

        Cell cell = bigTitleRow.getCell(1);
        cell.setCellStyle(bigTitle(workbook));
//        2019-12:2019年12  月份出货表      2019-01:2019年1  月份出货表
//        向单元格中写一句话   2012年8月份出货表
        cell.setCellValue(inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表");
//   ---------------     设置大标题结束     -------------------

//   ---------------     设置小标题开始     -----------------
        Row titleRow = sheet.createRow(1);
        titleRow.setHeightInPoints(26);
//        客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
        String[] titles = new String[]{"客户","合同号","货号","数量","工厂","工厂交期","船期","贸易条款"};
        for (int i = 1; i <= 8; i++) {
            cell = titleRow.createCell(i);
            cell.setCellStyle(title(workbook));
            cell.setCellValue(titles[i-1]);
        }
//   ---------------     设置小标题结束     -----------------


        //   ---------------     设置内容开始     -----------------
        int rowIndex = 2;
        Row row = null;
        for (ContractProductVo contractProductVo : cpVoList) {
            for (int i = 0; i < 6050; i++) {

            row = sheet.createRow(rowIndex);
            row.setHeightInPoints(24);
//            客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
            cell = row.createCell(1);
            cell.setCellValue(contractProductVo.getCustomName()); // 客户
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(2);
            cell.setCellValue(contractProductVo.getContractNo()); //合同号
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(3);
            cell.setCellValue(contractProductVo.getProductNo());//货号
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(4);
            cell.setCellValue(contractProductVo.getCnumber());//数量
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(5);
            cell.setCellValue(contractProductVo.getFactoryName());//工厂
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(6);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getDeliveryPeriod()) );//工厂交期
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(7);
            cell.setCellValue( new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getShipTime()) );//船期
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(8);
            cell.setCellValue(contractProductVo.getTradeTerms());// 贸易条款
//            cell.setCellStyle(text(workbook));
            rowIndex++;

            }
        }

//   ---------------     设置内容结束     -----------------

//        一个流 输出流
//        两个头 mine类型 和 打开方式
//        return "/cargo/print/contract-print";


        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);

        downloadUtil.download(byteArrayOutputStream,response,"出货表.xlsx");

    }



    @RequestMapping(value = "/printExcelEasyExcel",name = "使用easyExcel导出")
    public void printExcelEasyExcel(String inputDate) throws Exception{
        List<ContractProductVo> cpVoList = contractService.findContractProductVoListByShipTime(inputDate,getCompanyId());
//        一个流两个头儿

        String returnName = "出货表.xlsx";
        returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//设置mime类型
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+returnName);

        EasyExcel.write(response.getOutputStream()).head(ContractProductVo.class).sheet("出货表").doWrite(cpVoList);

    }
    @RequestMapping(value = "/printEasyExcelTemplate",name = "使用easyExcel借助模板导出")
    public void printEasyExcelTemplate(String inputDate) throws Exception{
        List<ContractProductVo> cpVoList = contractService.findContractProductVoListByShipTime(inputDate,getCompanyId());
//        一个流两个头儿
        Map map = new HashMap();
        map.put("time",inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表");

        String templateFilePath = session.getServletContext().getRealPath("/make/xlsprint/product.xlsx");

        String returnName = "出货表.xlsx";
        returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//设置mime类型
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+returnName);

//        为了构建excel的writer
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).head(ContractProductVo.class).withTemplate(templateFilePath).build();
//        获取即将写入的sheet对象
        WriteSheet sheet = EasyExcel.writerSheet().build();
        excelWriter.fill(map,sheet);
        excelWriter.fill(cpVoList,sheet);
        excelWriter.finish();

    }


    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线

        return style;
    }

    @RequestMapping(value = "/submit",name = "提交购销合同")
    public String submit(String id){
        Contract contract = new Contract();
        contract.setId(id);
        contract.setState(1);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do"; // 重定向到列表页面
    }
    @RequestMapping(value = "/cancel",name = "取消提交购销合同")
    public String cancel(String id){
        Contract contract = new Contract();
        contract.setId(id);
        contract.setState(0);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do"; // 重定向到列表页面
    }


}
